﻿using System.Xml;
using Basic.WxGatewayModular.Interface;
using Basic.WxRemoteModel.WxMsg;
using Basic.WxRemoteModel.WxMsg.Model;

namespace Basic.WxGatewayModular.lmpl
{
    internal class WxPlatformMsgService : IWxPlatformMsgService
    {
        private readonly IWxPlatformService _Platform;
        private static readonly string[] _Filters = new string[]
        {
            "InfoType",
            "CreateTime",
            "AppId"
        };
        public WxPlatformMsgService (IWxPlatformService service)
        {
            this._Platform = service;
        }

        public void SysEvent (XmlDocument doc)
        {
            XmlNode node = doc.FirstChild;
            string appId = node["AppId"].InnerText;
            string xml = this._Platform.DecryptXml(appId, node["Encrypt"].InnerText);
            WxPlatformMsg msg = this._GetMsg(xml, appId);
            new ReceivePlatformMsg
            {
                Msg = msg
            }.Send();
        }
        private WxPlatformMsg _GetMsg (string xml, string appId)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);
            XmlNode node = xmlDoc.FirstChild;
            WxPlatformMsg msg = new WxPlatformMsg
            {
                PlatformAppId = appId,
                EventType = node["InfoType"].InnerText,
                EventBody = [],
                CreateTime = long.Parse(node["CreateTime"].InnerText)
            };
            foreach (XmlNode i in node.ChildNodes)
            {
                if (!_Filters.Contains(i.Name))
                {
                    msg.EventBody.Add(i.Name, i.InnerText);
                }
            }
            return msg;
        }
    }
}
